package com.qiaoba.auth.handler;

import cn.hutool.core.util.StrUtil;
import com.qiaoba.auth.service.OnlineUserService;
import com.qiaoba.common.base.context.UserInfoContext;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 退出处理器
 *
 * @author ailanyin
 * @version 1.0
 * @since 2022/1/4 0004 下午 16:20
 */
@Component
@RequiredArgsConstructor
public class LogoutHandler implements LogoutSuccessHandler {

    private final OnlineUserService onlineUserService;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        String deviceSn = UserInfoContext.getDeviceSn();
        if (StrUtil.isNotBlank(deviceSn)) {
            // 删除缓存中的用户信息
            onlineUserService.deleteOne(deviceSn, true);
        }
    }
}
